/*
 * TextResource.java
 */

package xq.util.resource;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import static xq.util.CommonUtil.choose;
import static xq.util.IOUtil.readText;

/**
 *
 * @author ThorntonRP
 */
public class TextResource extends AbstractResource<String> {
	
	private static final long serialVersionUID = -2952022901948552673L;
	
	private String content;

	public TextResource(String resourceURI, String contentType, String content) throws URISyntaxException {
		super(resourceURI, choose(contentType, "text/plain"));
		this.content = content;
	}

	public TextResource(URI resourceURI, String contentType, String content) {
		super(resourceURI, choose(contentType, "text/plain"));
		this.content = content;
	}

	public TextResource(URL resourceURL, String contentType) throws IOException {
		super(resourceURL, choose(contentType, choose(resourceURL.openConnection().getContentType(), "text/plain")));
	}

	public TextResource(File resourceFile, String contentType) throws IOException {
		super(resourceFile, choose(contentType, choose(resourceFile.toURI().toURL().openConnection().getContentType(), "text/plain")));
	}
	
	@Override
	public String getContent() throws IOException {
		if (content == null) {
			if (getResourceURL() != null) {
				content = readText(getResourceURL());
			} else if (getResourceFile() != null) {
				content = readText(getResourceFile());
			}
		}
		return content;
	}
}
